<template>
  <div class="app-container">
    <div style="margin-bottom: 20px; display:flex;justify-content: space-between;">
      <div>
        <el-input
          size="small"
          v-model="listQuery.keyword"
          placeholder="请输入学员姓名/联系电话"
          style="width: 240px;"
          class="filter-item"
          @keyup.enter.native="submit"
        />
        <el-button
          size="mini"
          v-waves
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          style="margin-left: 20px;"
          @click="submit"
        >搜索</el-button>
      </div>
      <div style="display:flex">
        <el-button size="mini" @click="importStudentDialog=true">导入学员</el-button>
        <el-button type="primary" size="mini" @click="addStudentDialog=true">添加学员</el-button>
      </div>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      height="700px"
      :element-loading-text="global.loadingStr"
      :header-cell-style="{background:global.mainColor}"
    >
      <el-table-column label="学员姓名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄 | 性别" align="center">
        <template slot-scope="{row}">
          <span>{{ ageFormatter(row.birthday) }} | {{ row.gender===1?'男':"女"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="学习课程 ｜套餐" align="center" width="200">
        <template slot-scope="{row}">
          <el-button
            v-if="row.courseSetMeal==='详情'"
            type="text"
            @click="handleStudentInfo(row)"
          >{{row.courseSetMeal}}</el-button>
          <span v-else>{{row.courseSetMeal}}</span>
        </template>
      </el-table-column>
      <el-table-column label="已上｜剩余（课时）" align="center" width="200">
        <template slot-scope="{row}">
          <el-button
            v-if="row.count==='详情'"
            type="text"
            @click="handleStudentInfo(row)"
          >{{row.count}}</el-button>
          <span v-else>{{row.count}}</span>
        </template>
      </el-table-column>
      <el-table-column label="学员家长" align="center">
        <template slot-scope="{row}">
          <span>{{ row.parentName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="家长备注" align="center">
        <template slot-scope="{row}">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
          <el-button type="text" @click="handleLessonSchedule(row)">课表</el-button>
          <el-button v-if="row.courseArrangementCount>0" type="text" @click="handleSchedule(row)">排课</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.currentPage"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
    <!-- 导入学员 -->
    <el-dialog
      title="导入学员（Excel）"
      :visible.sync="importStudentDialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      width="500px">
      <el-row style="margin-bottom:10px">
        <el-upload
          style="margin-right:10px"
          action="#"
          accept=".xlsx, .xls"
          :limit="2"
          list-type
          :on-change="removeLastFile"
          :http-request="handleOnsuccess"
          :on-exceed="handleOnExceed"
        >
          <el-button size="small">导入文件</el-button>
        </el-upload>
      </el-row>
      <el-row>
        <el-col>
          <i class="el-icon-warning" /> 请先
          <el-button type="text">
            <a
              href="http://ossdev0.oss-cn-shenzhen.aliyuncs.com/%E5%AD%A6%E7%94%9F%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"
            >下载模板</a>
          </el-button>
          ，按格式填写，再导入！
        </el-col>
      </el-row>
      <el-row>
        <span style="color:red;font-size:12px">
          <i class="el-icon-warning"></i> 请勿修改模板文件名，避免导入失败
        </span>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importStudentDialog = false">取 消</el-button>
        <el-button type="primary" @click="confimImportStudent">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加学员 -->
    <el-dialog
      title="添加学员"
      :visible.sync="addStudentDialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="addStudentFormRef.resetFields()"
      width="500px">
      <el-row style="width:70%">
        <JblForm
          :ref-name.sync="addStudentFormRef"
          :form.sync="addStudentForm"
          :value-data="addStudentForm.valueData"
        >
          <template v-slot:form-avatarStorageUrl>
            <el-upload
              class="avatar-uploader"
              action="#"
              accept=".jpg, .jpeg, .png, .JPEG, .BMP"
              :http-request="uploadImg"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="addStudentForm.valueData.avatarStorageUrl"
                :src="addStudentForm.valueData.avatarStorageUrl"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </template>
        </JblForm>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="(addStudentFormRef.resetFields(),addStudentDialog = false)">取 消</el-button>
        <el-button type="primary" @click="handleAddStudent">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 学习课程套餐详情 -->
    <el-dialog
      :title="studentInfo.title"
      :visible.sync="studentInfo.dialog"
      @close="studentInfoClose"
      width="60%">
      <el-row>
        <el-tabs v-model="studentInfo.activeName">
          <el-tab-pane class="studentInfo" label="基本信息" name="info">
            <el-table
              :key="tableKey"
              :data="studentInfo.data"
              border
              fit
              highlight-current-row
              style="width: 100%;"
              :element-loading-text="global.loadingStr"
              :header-cell-style="{background:global.mainColor}"
            >
              <el-table-column label="头像" align="center">
                <template slot-scope="{row}">
                  <el-image :src="row.avatarStorageUrl"></el-image>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="姓名" align="center"></el-table-column>
              <el-table-column prop="birthday" label="年龄" align="center">
                <template slot-scope="{row}">
                  {{ ageFormatter(row.birthday) }}
                </template>
              </el-table-column>
              <el-table-column prop="aa" label="性别" align="center">
                <template slot-scope="{row}">
                  <span>{{ row.gender===1?"男":"女" }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="phone" label="联系电话" align="center" />
            </el-table>
          </el-tab-pane>
          <el-tab-pane class="studentInfo" label="学习课程" name="course">
            <div
              style="padding:20px 0; border-bottom: 1px dashed #eee"
              v-for="(item,index) in studentInfo.studentData"
              :key="index"
            >
              <el-row type="flex" justify="space-around" style="margin-bottom:10px">
                <el-col :span="8" align="middle" >课程：<span class="detail-title">{{item.scheduleName}}</span></el-col>
                <el-col :span="8" align="middle" >套餐：<span class="detail-title">{{item.setMealName}}</span></el-col>
                <el-col :span="8" align="middle" >老师：<span class="detail-title">{{item.teacheName}}</span></el-col>
              </el-row>
              <el-row>
                <el-table
                  :data="item.data"
                  border
                  fit
                  highlight-current-row
                  style="width: 100%;"
                  :element-loading-text="global.loadingStr"
                  :header-cell-style="{background:global.mainColor}"
                >
                  <el-table-column prop="price" label="价格" align="center" />
                  <el-table-column prop="teachingMethods" label="授课方式" align="center" />
                  <el-table-column prop="count" label="已上 ｜ 请假（节数）" align="center" />
                  <el-table-column prop="surplusCount" label="剩余（节数）" align="center" />
                </el-table>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-row>
      <el-row v-if="studentInfo.activeName==='course'" type="flex" justify="end">
        <el-pagination
          :current-page="studentInfo.page"
          :page-sizes="[3,10, 50]"
          :page-size="studentInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="studentInfo.total"
          :background="true"
          @size-change="handleSizestudentInfoChange"
          @current-change="handlestudentInfoChange"
        />
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="studentInfo.dialog = false">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 排课 -->
    <el-dialog title="排课" :visible.sync="scheduleCourseForm.dialog" width="650px" @close="handleCacelPreview">
      <el-row class="scheduleCourseForm" style="width:620px">
        <JblForm
          :ref-name.sync="scheduleCourseFormRef"
          :form.sync="scheduleCourseForm"
          :value-data="scheduleCourseForm.valueData"
        >
          <!-- 每周上课节数 -->
          <template v-slot:form-skCount>
            <el-row>
              <el-col :span="10">
                <el-select
                  size="small"
                  v-model="scheduleCourseForm.valueData.skCount"
                  placeholder="请选择节数"
                >
                  <el-option
                    v-for="item in scheduleCourseForm.valueData.lessonCount"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col v-for="(week,index) in scheduleCourseForm.valueData.skCount" :key="index">
                <el-select
                  style="width:100px"
                  size="mini"
                  v-model="weekValue[index]"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in weekOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>-
                <el-time-picker
                  style="width:170px"
                  size="mini"
                  v-model.number="dateValue[index]"
                  format="HH 点 mm 分"
                  value-format="timestamp"
                  placeholder="任意时间点"
                />
              </el-col>
            </el-row>
          </template>

          <!-- 上课节数时间 -->
          <template v-slot:form-mjTime>
            <el-row>
              <el-col
                :span="24"
                v-for="(week,index) in scheduleCourseForm.valueData.lessonCount"
                :key="index"
              >
                <span>第{{index+1}}节:</span>
                <el-date-picker
                  style="width:160px"
                  size="mini"
                  v-model.number="ymValue[index]"
                  type="date"
                  value-format="timestamp"
                  placeholder="选择日期"
                ></el-date-picker>-
                <el-time-picker
                  size="mini"
                  style="width:140px"
                  v-model.number="dateValue[index]"
                  format="HH 点 mm 分"
                  value-format="timestamp"
                  placeholder="任意时间点"
                />
              </el-col>
            </el-row>
          </template>
        </JblForm>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="scheduleCourseForm.dialog=false">取 消</el-button>
        <el-button type="primary" @click="handlePreview">排课预览</el-button>
      </span>
    </el-dialog>
    <!-- 排课预览 -->
    <el-dialog
      title="排课预览 "
      :visible.sync="previewDialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="cacelPreview"
      width="600px"
    >
      <el-row type="flex" justify="center">
        <el-table
          border
          :data="previewData"
          :header-cell-style="{background:global.mainColor}"
          style="width: 100%"
        >
          <el-table-column label="节数" width="100" align="center">
            <template slot-scope="scope">
              <span>第 {{scope.$index+1}} 节</span>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="时间" align="center" />
          <el-table-column label="状态" width="200" align="center">
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="dark"
                :content="scope.row.studentName||'正常'"
                placement="top-start"
              >
                <span>{{scope.row.status}}</span>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <span slot="footer">
        <el-button type="primary" @click="confimCourse">确认排课</el-button>
        <el-button @click="cacelPreview">取消</el-button>
      </span>
    </el-dialog>
    <!-- 课表 -->
    <el-dialog
      :visible.sync="lessonSchedule.dialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @close="lessonScheduleClose"
      width="1000px">
      <el-row slot="title" style="margin-bottom:10px">
        <el-col :span="4">
          <span style="font-size:18px">学员: {{currentRow.name}}</span>
        </el-col>
        <el-col :span="7">
          <span style="font-size:18px">联系电话: {{currentRow.phone}}</span>
        </el-col>
      </el-row>
      <el-row style="margin-bottom:20px" type="flex" justify="space-between">
        <el-col :span="11">
          <span>日期:</span>
          <el-date-picker
            @change="dateChange"
            v-model="lessonSchedule.date"
            size="mini"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            value-format="timestamp"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-col>
        <el-col style="line-height:30px" :span="6">
          <el-radio-group v-model="lessonSchedule.allSchedule" @change="allScheduleRadio">
            <el-radio
              v-for="(item,index) in lessonSchedule.radioGroup"
              :key="index"
              :label="item.id"
            >{{item.name}}</el-radio>
          </el-radio-group>
        </el-col>
        <el-col :span="6">
          <span>课程:</span>
          <el-select
            size="mini"
            v-model="lessonSchedule.courseValue"
            placeholder="请选择"
            @change="courseValueChange"
          >
            <el-option
              v-for="item in scheduleCourseVOoptions"
              :key="item.scheduleCourseId"
              :label="item.scheduleCourseName"
              :value="item.scheduleCourseId"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row type="flex" justify="center">
        <el-table
          border
          :data="lessonSchedule.data"
          empty-text="没有上课的课程哦~"
          :header-cell-style="{background:global.mainColor}"
          style="width: 100%"
          height="500"
        >
          <el-table-column label="上课日期" align="center" width="120">
            <template slot-scope="scope">
              <span>{{scope.row.courseBeginTime | parseTime('{y}-{m}-{d}')}}</span>
            </template>
          </el-table-column>
          <el-table-column label="上课时间" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.courseBeginTime | parseTime('{h}:{i}')}}</span>
            </template>
          </el-table-column>
          <el-table-column label="课程名称 | 套餐" width="180" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.scheduleCourseName}} | {{scope.row.setMealName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="节数 ｜ 课时" width="180" align="center">
            <template slot-scope="scope">
              <span>第{{scope.row.num+1}}节 | {{scope.row.classHour}}分钟</span>
            </template>
          </el-table-column>
          <el-table-column prop="teachName" label="老师" align="center" />
          <el-table-column label="考勤" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.status | lessonScheduleStatus}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.status===1"
                type="text"
                @click="handleStudentClock(scope.row)"
              >打卡</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row type="flex" justify="end">
        <el-pagination
          :current-page="lessonSchedule.page"
          :page-sizes="[10,20,50]"
          :page-size="lessonSchedule.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="lessonSchedule.total"
          :background="true"
          @size-change="handleLessonScheduleChangeSize"
          @current-change="handLessonScheduleChange"
        />
      </el-row>
      <span slot="footer">
        <el-button type="primary" @click="(lessonSchedule.dialog=false)">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import JblForm from '@/components/JblForm'
import axios from 'axios'
import {
  studentList,
  addStudent,
  getCourseSetMealVOPage,
  getCourseSetMealVO,
  verificationTime,
  studentLesson,
  getScheduleCourseVO,
  getStudentLesson,
  studentClock
} from '@/api/student'
export default {
  name: 'StudentList',
  directives: { waves },
  components: { Pagination, JblForm },
  data() {
    var validatePhone = (rule, value, callback) => {
      if (value === null) {
        callback(new Error('请输入手机号码'))
      } else if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    return {
      currentRow: {}, // 当前行信息
      addStudentDialog: false, // 添加学员 dialog
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        currentPage: 1,
        pageSize: 10,
        businessId: this.$store.getters.businessId,
        keyword: ''
      },
      addStudentFormRef: {},
      // 导入学员
      importStudentDialog: false,
      importFileUrl: '', // 文件地址
      // 添加学员
      addStudentForm: {
        labelWidth: '100px',
        data: [
          {
            type: 'slot',
            show: () => {},
            labelWidth: '80px',
            prop: 'avatarStorageUrl',
            label: '学员头像',
            rules: [
              { required: true, message: '请上传头像', trigger: 'change' }
            ]
          },
          {
            type: 'input',
            labelWidth: '80px',
            prop: 'name',
            label: '学员姓名',
            placeholder: '请输入学员姓名',
            rules: [
              { required: true, message: '请输入学员姓名', trigger: 'blur' },
              {
                min: 1,
                max: 20,
                message: '长度在 1 到 10 个字符',
                trigger: 'blur'
              }
            ]
          },
          {
            type: 'ymdDatetime',
            labelWidth: '80px',
            valueFormat: 'timestamp',
            prop: 'birthday',
            label: '学员年龄',
            placeholder: '请输入学员出生日期',
            pickerOptions: () => {
              return {
                disabledDate(date) {
                  return date.getTime() >= Date.now() - 8.64e7
                }
              }
            },
            rules: [
              { required: true, message: '请输入学员出生日期', trigger: 'change' }
            ]
          },
          {
            type: 'radioGroup',
            size: 'small',
            labelWidth: '80px',
            prop: 'gender',
            label: '学员性别',
            radioGroup: () => {
              return [
                {
                  label: '男',
                  value: 1
                },
                {
                  label: '女',
                  value: 2
                }
              ]
            },
            rules: [
              {
                type: 'number',
                required: true,
                message: '请选择学员性别',
                trigger: 'change'
              }
            ]
          },
          {
            type: 'inputNumber',
            labelWidth: '110px',
            prop: 'phone',
            label: '家长联系电话',
            placeholder: '请输入家长联系电话',
            rules: [{ required: true, validator: validatePhone, trigger: 'blur' }]
          }
        ],
        valueData: {
          avatarStorageUrl: 'https://ossdev0.jiabala.com/BcGQmdmLDWDaC',
          gender: 1,
          isDelete: 0,
          businessId: this.$store.getters.businessId
        }
      },
      // 学员信息
      studentInfo: {
        page: 1,
        pageSize: 3,
        total: 0,
        title: '',
        dialog: false,
        activeName: 'info',
        data: [],
        studentData: [] // 学习课程
      },
      // 排课
      scheduleCourseFormRef: {},
      scheduleCourseForm: {
        dialog: false,
        labelWidth: '100px',
        data: [
          {
            type: 'text',
            labelWidth: '80px',
            prop: 'name',
            label: '学员姓名'
          },
          {
            type: 'text',
            labelWidth: '80px',
            prop: 'scheduleName',
            label: '课程名称'
          },
          {
            type: 'select',
            required: true,
            labelWidth: '80px',
            prop: 'setMealId',
            label: '套餐名称',
            placeholder: '请选择套餐',
            selectOption: () => {
              return this.scheduleNameOption
            },

            rules: [
              { required: true, message: '请选择套餐', trigger: 'change' }
            ]
          },
          {
            type: 'text',
            labelWidth: '80px',
            prop: 'teacheName',
            label: '授课老师'
          },
          {
            type: 'text',
            labelWidth: '80px',
            prop: 'ksTime',
            label: '课时时长'
          },
          {
            type: 'radioGroup',
            size: 'small',
            required: true,
            labelWidth: '80px',
            prop: 'teachingMethods',
            label: '排课方式',
            radioGroup: () => {
              return [
                {
                  label: '按周排课',
                  value: 1
                },
                {
                  label: '按节排课',
                  value: 2
                }
              ]
            },
            rules: [
              {
                type: 'number',
                required: true,
                message: '请选择排课方式',
                trigger: 'change'
              }
            ]
          },
          {
            type: 'datetime',
            show: () => {
              return this.scheduleCourseForm.valueData.teachingMethods === 1
            },
            size: 'small',
            labelWidth: '110px',
            prop: 'startTimes',
            label: '排课起始日期',
            placeholder: '请输入排课起始日期',
            pickerOptions: () => {
              return {
                disabledDate(time) {
                  return time.getTime() < Date.now() - 8.64e7// 如果没有后面的-8.64e7就是不可以选择今天的
                }
              }
            },
            rules: [
              {
                type: 'date',
                required: true,
                message: '请选择排课起始日期',
                trigger: 'change'
              }
            ]
          },
          {
            type: 'slot',
            required: true,
            show: () => {
              return this.scheduleCourseForm.valueData.teachingMethods === 1
            },
            prop: 'skCount',
            labelWidth: '110px',
            label: '每周上课节数',
            rules: [
              {
                type: 'date',
                required: true,
                message: '请输入每周上课节数',
                trigger: 'change'
              }
            ]
          },
          {
            type: 'slot',
            show: () => {
              return this.scheduleCourseForm.valueData.teachingMethods === 2
            },
            prop: 'mjTime',
            labelWidth: '110px',
            label: '上课时间'
          }
        ],
        valueData: {
          imageUrl: '',
          name: '',
          setMealName: '', // 套餐名称
          skCount: 1,
          lessonCount: 1,
          ksTime: '',
          teacheName: '',
          classHour: '',
          scheduleName: '',
          teachingMethods: 1,
          startTimes: null
        }
      },
      // 选择套餐
      scheduleNameOption: [],
      previewDialog: false,
      previewData: [], // 排课预览数据
      pkStartTime: [], // 排课开始时间
      pkEndTime: [], // 排课结束时间
      // 周
      weekOptions: [
        {
          label: '每周一',
          value: 0
        },
        {
          label: '每周二',
          value: 1
        },
        {
          label: '每周三',
          value: 2
        },
        {
          label: '每周四',
          value: 3
        },
        {
          label: '每周五',
          value: 4
        },
        {
          label: '每周六',
          value: 5
        },
        {
          label: '每周日',
          value: 6
        }
      ],
      weekValue: [],
      // 时分
      dateValue: [],
      // 年
      ymValue: [],
      // 课表
      lessonSchedule: {
        dialog: false,
        data: [],
        page: 1,
        pageSize: 10,
        total: 0,
        date: null,
        allSchedule: null,
        courseValue: null,
        radioGroup: [],
        courseBeginTime: '',
        courseEndTime: ''
      },
      // 课程select
      scheduleCourseVOoptions: []
    }
  },
  filters: {
    lessonScheduleStatus(v) {
      switch (v) {
        case 1:
          v = '未开始'
          break
        case 2:
          v = '已签到'
          break
        case 3:
          v = '已请假'
          break
        case 4:
          v = '缺课'
          break
        case 5:
          v = '已评价'
          break
      }
      return v
    }
  },
  watch: {
    'addStudentForm.valueData.gender'(sex) {
      if (sex === 2) {
        this.addStudentForm.valueData.avatarStorageUrl = 'https://ossdev0.jiabala.com/tcOYpNdwaVHiB'
      } else {
        this.addStudentForm.valueData.avatarStorageUrl = 'https://ossdev0.jiabala.com/BcGQmdmLDWDaC'
      }
    },
    'scheduleCourseForm.valueData.setMealId'(v) {
      const obj = this.scheduleNameOption.find(i => i.setMealId === v)
      this.scheduleCourseForm.valueData = obj
    },
    'scheduleCourseForm.valueData.teachingMethods'(v) {
      this.handleCacelPreview()
    }
  },
  created() {},
  mounted() {
    this.getList()
  },
  methods: {
    handleOnsuccess(response, file, fileList) {
      this.importFileUrl = response.file
    },
    // 移除上一个文件
    removeLastFile(files, fileList) {
      if (fileList.length > 1) {
        this.importFileUrl = fileList.splice(0, 1)
      }
    },
    handleOnExceed(file, fileList) {
      this.$message({
        message: '当前限制上传 1 个文件，请先删除上一个文件，再上传',
        type: 'error',
        duration: 5000
      })
    },
    // 导入学员
    confimImportStudent() {
      // console.log(this.importFileUrl, '777777777')
      if (!this.importFileUrl) {
        return this.$message({
          message: '请先导入文件',
          type: 'error'
        })
      }
      const uploadApi = '/jbl-business/api/merchant/v1/student/import'
      const param = new FormData()
      param.append('file', this.importFileUrl)
      param.append('businessId', this.$store.getters.businessId)
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Access-Control-Allow-Origin': '*'
        }
        // responseType: 'blob'
      }
      axios
        .post(process.env.VUE_APP_BASE_API + uploadApi.substr(1), param, config)
        .then(response => {
          if (response.data.successCount === response.data.total) {
            TDAPP.onEvent('导入学员')
            this.$message({ message: '操作成功', type: 'success' })
            this.getList()
            this.importStudentDialog = false
          } else {
            this.$message({
              message: '操作失败,请查看下载文件',
              type: 'error',
              duration: 0,
              showClose: true
            })
            window.location.href =
              process.env.VUE_APP_BASE_API +
              '/api/merchant/v1/student/downloadErrors?fileName=' +
              response.data.errorsFile
          }
        })
    },
    // 学员信息
    handleStudentInfo(row) {
      this.studentInfo.title = row.name
      this.currentRow = row
      this.studentInfo.data = [row]
      this.getStudentCourse(row)
      this.studentInfo.dialog = true
    },
    getStudentCourse(row) {
      getCourseSetMealVOPage({
        studentId: row.id,
        businessId: this.$store.getters.businessId,
        currentPage: this.studentInfo.page,
        pageSize: this.studentInfo.pageSize
      }).then(res => {
        const data = res.data
        this.studentInfo.total = data.total
        this.studentInfo.studentData = data.records.map((i, index) => {
          return {
            scheduleName: i.scheduleName,
            setMealName: i.setMealName,
            teacheName: i.teacheName,
            data: [
              {
                price: `￥${i.price || 0}`,
                teachingMethods: i.teachingMethods,
                count: `${i.alreadyInClassCount} | ${i.leaveRequestedCount}`,
                surplusCount: i.surplusCount
              }
            ]
          }
        })
      })
    },
    // 学习课程 表格分页
    handleSizestudentInfoChange(val) {
      this.studentInfo.pageSize = val
      this.getStudentCourse(this.currentRow)
    },
    handlestudentInfoChange(val) {
      this.studentInfo.page = val
      this.getStudentCourse(this.currentRow)
    },
    studentInfoClose() {
      this.studentInfo.page = 1
      this.studentInfo.pageSize = 3
    },
    // 排课
    handleSchedule(row) {
      this.currentRow = row
      this.scheduleCourseForm.valueData.name = row.name
      getCourseSetMealVO({
        studentId: row.id,
        businessId: this.$store.getters.businessId
      }).then(res => {
        this.scheduleCourseForm.valueData = res.data[0]
        this.scheduleCourseForm.valueData.teachingMethods = +res.data[0].teachingMethods
        this.scheduleNameOption = res.data
        this.scheduleNameOption.forEach(i => {
          i.name = row.name
          i.label = i.setMealName
          i.value = i.setMealId
          i.ksTime = `每节${i.classHour}分钟 | 共${i.lessonCount}节`
        })
      })
      this.scheduleCourseForm.dialog = true
    },
    getMonday(dd) { // 指定日期的周一
      var week = dd.getDay() // 获取时间的星期数
      var minus = week ? week - 1 : 6
      dd.setDate(dd.getDate() - minus) // 获取minus天前的日期
      var y = dd.getFullYear()
      var m = dd.getMonth() + 1 // 获取月份
      var d = dd.getDate()
      return `${y} - ${m} - ${d}`
    },
    getWeek(n, dd) {
      const weekRange = []
      const d = this.getMonday(dd)
      // const d = this.$options.filters.parseTime(this.scheduleCourseFrom.valueData.startTimes, '{y}-{m}-{d}')
      for (var i = 0; i < 7 * n; i++) {
        const d1 = Date.parse(d.replace(/-/g, '/'))
        let date = new Date(d1)
        date = date.valueOf()
        date = date + i * 24 * 60 * 60 * 1000
        date = new Date(date)
        let mymonth = date.getMonth() + 1
        let myday = date.getDate()
        const myyear = date.getFullYear()
        const year = (myyear > 200) ? myyear : 1900 + myyear
        if (mymonth < 10) { mymonth = '0' + mymonth }
        if (myday < 10) { myday = '0' + myday }
        const outputdate = year + '-' + mymonth + '-' + myday
        weekRange.push(outputdate)
      }
      // console.log(weekRange,'weekRange');
      return weekRange
    },
    // 排课预览
    handlePreview() {
      let confim = false
      this.scheduleCourseFormRef.validate(valid => {
        if (valid) {
          confim = true
          return
        } else {
          return false
        }
      })
      if (!confim) return
      if (this.scheduleCourseForm.valueData.teachingMethods === 1) {
        // 按周排课
        const arr = []
        const agn = Math.ceil(
          this.scheduleCourseForm.valueData.lessonCount /
            this.scheduleCourseForm.valueData.skCount
        )
        const dd = Object.assign({}, this.scheduleCourseForm.valueData)
        const nowTime = dd.startTimes
        const nextWeek = this.getWeek(agn, new Date(dd.startTimes))
        console.log(new Date(dd.startTimes))
        // const nowTime = this.$options.filters.parseTime(new Date(), '{y}')
        for (let i = 0; i < agn; i++) {
          this.dateValue.forEach((j, index) => {
            const start = this.$options.filters.parseTime(j, '{h}:{i}')
            const end = this.$options.filters.parseTime(
              j + this.scheduleCourseForm.valueData.classHour * 60 * 1000,
              '{h}:{i}'
            )
            const week = this.weekOptions.find(
              j => j.value === this.weekValue[index]
            ).label
            arr.push({
              week: nextWeek[this.weekValue[index]],
              start: `${
                nextWeek[this.weekValue[index] + i * 7]
              } ${start}`,
              end: `${
                nextWeek[this.weekValue[index] + i * 7]
              } ${end}`,
              date: `${
                nextWeek[this.weekValue[index] + i * 7]
              } ${week} ${start}-${end}`
              // date: `${new Date(`${nowTime}-${nextWeek[this.weekValue[index] + i * 7]} ${start}`)}`
            })
          })
        }
        const sarr = arr.filter(i => {
          return new Date(i.start).valueOf() > nowTime
        })
        this.previewData = sarr.slice(
          0,
          this.scheduleCourseForm.valueData.lessonCount
        )
        const startTime = []
        const endTime = []

        this.previewData.forEach(i => {
          startTime.push(new Date(i.start).valueOf())
          endTime.push(new Date(i.end).valueOf())
        })
        this.pkStartTime = startTime
        this.pkEndTime = endTime
      } else {
        // 按节排课
        this.ymValue.forEach((i, index) => {
          // 年月日
          const y = this.$options.filters.parseTime(i, '{y}-{m}-{d}')
          const w = new Date(i).getDay()
          // 时分
          const h = this.$options.filters.parseTime(
            this.dateValue[index],
            '{h}:{i}'
          )
          // 结束时间
          const e = this.$options.filters.parseTime(
            this.dateValue[index] +
              this.scheduleCourseForm.valueData.classHour * 60 * 1000,
            '{h}:{i}'
          )
          const ww = ['日', '一', '二', '三', '四', '五', '六']
          this.previewData.push({
            date: `${y} 每周${ww[w]} ${h}-${e}`
          })
          this.pkStartTime.push(new Date(`${y} ${h}`).valueOf())
          this.pkEndTime.push(new Date(`${y} ${e}`).valueOf())
        })
      }
      // if (
      //   this.previewData.length < this.scheduleCourseForm.valueData.lessonCount
      // ) {
      //   return this.$message({
      //     message: '排课节数未填写完整',
      //     type: 'error'
      //   })
      // }
      // 排课预览
      verificationTime({
        startTimes: this.pkStartTime,
        endTimes: this.pkEndTime,
        lessonTime: this.scheduleCourseForm.valueData.classHour * 60 * 1000,
        businessId: this.$store.getters.businessId,
        studentId: this.currentRow.id,
        scheduleCourseId: Number(this.scheduleCourseForm.valueData.setMealId)
      }).then(res => {
        const vArr = res.data
        this.previewData.forEach((i, index) => {
          let v = ''
          switch (vArr[index].conflictType) {
            case 1:
              v = '时间冲突'
              break
            case 2:
              v = '老师冲突'
              break
            default:
              v = '正常'
              break
          }
          this.$set(i, 'status', v)
          this.$set(i, 'studentName', vArr[index].studentName)
        })
        this.previewDialog = true
      })
    },
    // 取消排课预览
    handleCacelPreview() {
      this.weekValue = []
      this.dateValue = []
      this.ymValue = []
      this.pkStartTime = []
      this.pkEndTime = []
    },
    cacelPreview() {
      this.previewDialog = false
      this.previewData = []
      this.pkStartTime = []
      this.pkEndTime = []
    },
    // 确认排课
    confimCourse() {
      if (this.scheduleCourseForm.valueData.teachingMethods === 1) {
        TDAPP.onEvent('按周排课使用次数')
      }else{
        TDAPP.onEvent('按节排课次数');
      }
      studentLesson({
        scheduleCourseId: this.scheduleCourseForm.valueData.scheduleCourseId,
        scheduleCourseName: this.scheduleCourseForm.valueData.scheduleName,
        setMealId: this.scheduleCourseForm.valueData.setMealId,
        startTimes: this.pkStartTime,
        endTimes: this.pkEndTime,
        businessId: this.$store.getters.businessId,
        businessName: this.$store.getters.name,
        teachName: this.scheduleCourseForm.valueData.teacheName,
        courseId: this.scheduleCourseForm.valueData.courseId,
        courseName: this.scheduleCourseForm.valueData.courseName,
        studentId: this.currentRow.id
      }).then(res => {
        this.previewDialog = false
        this.scheduleCourseForm.dialog = false
        this.handleCacelPreview()
        this.getList()
      })
    },
    // 课表日期选择
    dateChange(v) {
      this.lessonSchedule.courseValue = null
      this.lessonSchedule.allSchedule = ''
      this.courseBeginTime = v[0]
      this.courseEndTime = v[1]
      this.getStudentLesson()
    },
    // 课表单选框
    allScheduleRadio(v) {
      this.lessonSchedule.courseValue = null
      this.lessonSchedule.date = null
      if (v) {
        this.courseBeginTime = v.split(',')[0]
        this.courseEndTime = v.split(',')[1]
      } else {
        this.courseBeginTime = null
        this.courseEndTime = null
      }
      this.getStudentLesson()
    },
    // 课表课程套餐
    courseValueChange(v) {
      this.lessonSchedule.date = null
      this.lessonSchedule.allSchedule = ''
      this.courseBeginTime = null
      this.courseEndTime = null
      this.getStudentLesson()
    },
    // 查询课表
    getStudentLesson() {
      getStudentLesson({
        currentPage: this.lessonSchedule.page,
        pageSize: this.lessonSchedule.pageSize,
        businessId: this.$store.getters.businessId,
        courseBeginTime: this.courseBeginTime,
        courseEndTime: this.courseEndTime,
        scheduleCourseId: this.lessonSchedule.courseValue,
        studentId: this.currentRow.id
      }).then(res => {
        this.lessonSchedule.data = res.data.data.records
        this.lessonSchedule.total = res.data.data.total
      })
    },
    // 课表
    handleLessonSchedule(row) {
      TDAPP.onEvent('查看课表')
      this.currentRow = row
      const firstDay = new Date()
      firstDay.setDate(1)
      firstDay.setMonth(0)
      const lastDay = new Date()
      lastDay.setFullYear(lastDay.getFullYear() + 1)
      lastDay.setDate(0)
      lastDay.setMonth(-1)
      const end = new Date()
      const start = new Date()
      start.setTime(new Date(new Date().getFullYear(), new Date().getMonth(), 1))
      // console.log(Date.parse(start) );
      // start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      this.lessonSchedule.radioGroup = [
        {
          name: '全部',
          id: null
        },
        {
          name: '本年',
          id: `${firstDay.valueOf()},${lastDay.valueOf()}`
        },
        {
          name: '本月',
          id: `${new Date(start).valueOf()},${new Date(end.getFullYear(), end.getMonth() + 1, 0).valueOf()}`
        }
      ]
      getScheduleCourseVO({
        businessId: this.$store.getters.businessId,
        studentId: row.id
      }).then(res => {
        this.scheduleCourseVOoptions = res.data.data
      })
      this.getStudentLesson()
      this.lessonSchedule.dialog = true
    },
    lessonScheduleClose() {
      this.lessonSchedule.page = 1
      this.lessonSchedule.pageSize = 10
    },
    handLessonScheduleChange(val) {
      this.lessonSchedule.page = val
      this.getStudentLesson()
    },
    handleLessonScheduleChangeSize(val) {
      this.lessonSchedule.pageSize = val
      this.getStudentLesson()
    },
    // 课表打卡
    handleStudentClock(row) {
      studentClock({
        id: row.id
      }).then(res => {
        this.$message({
          message: '打卡成功',
          type: 'success'
        })
        this.getStudentLesson()
      })
    },
    // 学员头像上传
    uploadImg(params) {
      const raw = {
        raw: params.file,
        name: params.file.name
      }
      this.uploadImgToOss(raw).then(response => {
        const { imgUrl } = response
        this.addStudentForm.valueData.avatarStorageUrl = imgUrl
      })
    },
    handleAddStudent() {
      this.addStudentFormRef.validate(valid => {
        if (valid) {
          addStudent(this.addStudentForm.valueData).then(res => {
            this.addStudentDialog = false
            TDAPP.onEvent('添加学员')
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            this.addStudentDialog = false
            this.getList()
          })
        } else {
          return false
        }
      })
    },
    handleAvatarSuccess(res, file) {
      // this.addStudentForm.valueData.avatarStorageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/bmp'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG。png、bmp 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    getList() {
      this.listLoading = false
      studentList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.list.forEach(i => {
          // i.birthday = this.ageFormatter(i.birthday)
          if (i.vos.length > 1) {
            i.courseSetMeal = '详情'
            i.count = '详情'
          }
          if (i.vos.length === 1) {
            i.courseSetMeal = `${i.vos[0].scheduleName} | ${i.vos[0].setMealName}`
            i.count = `${i.vos[0].alreadyInClassCount} | ${i.vos[0].surplusCount}`
          }
        })
        this.listLoading = false
      })
    },
    submit() {
      this.listQuery.currentPage = 1
      this.getList()
    },
    ageFormatter(v) {
      // 时间戳 this.$options.filters.parseTime(new Date().valueOf(), '{y}')
      const nowDate = Number(
        this.$options.filters.parseTime(new Date().valueOf(), '{y}')
      )
      const birthday = Number(this.$options.filters.parseTime(v, '{y}'))
      const y = nowDate - birthday >= 1 ? nowDate - birthday : 1
      return y
    }
  }
}
</script>

<style lang="scss" scoped>
.studentInfo {
  height: 500px;
  overflow: hidden;
  overflow-y: auto;
}
.scheduleCourseForm {
  height: 550px;
  overflow: hidden;
  overflow-y: auto;
}
.detail-title{
  font-size: 15px;
  font-weight: 600;
}
/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  border-radius: 50%;
}
/deep/.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 18px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border-radius: 50%;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
}
</style>
